
#import "MainPageController.h"
#import "NavigationView.h"
#import "FunctionCell.h"
#import "SelectionCell.h"
#import "PageModels.h"
#import "IndexModel.h"
#import "MenuModel.h"
#import "FishModel.h"
#import "IslandsController.h"
#import "SchoolController.h"
#import "AticleModel.h"
#import "CGFdbmBase.h"
#import "CitysController.h"
#import "WeatherController.h"
#import "CityButton.h"
#import "MainPageModel.h"
#import "MainPageTableview.h"
#import "MJRefresh.h"
#import "SeleCtContrl.h"
#import "SouSuoViewController.h"
#import "IslandsController.h"
#import "LoginController.h"
#import "OtherInformationCtrl.h"
#import "WetherModel.h"
#import "CityModel.h"
#import "WeathForecastModel.h"
#import "FunSelectController.h"
#import "ForumClickController.h"
#import <BaiduMapAPI_Base/BMKBaseComponent.h>//引入base相关所有的头文件
#import <BaiduMapAPI_Map/BMKMapComponent.h>//引入地图功能所有的头文件
#import <BaiduMapAPI_Search/BMKSearchComponent.h>//引入检索功能所有的头文件
#import <BaiduMapAPI_Cloud/BMKCloudSearchComponent.h>//引入云检索功能所有的头文件
#import <BaiduMapAPI_Location/BMKLocationComponent.h>//引入定位功能所有的头文件
@interface MainPageController ()<MainPageTableviewDeleget,SeleCtContrlDeleget,BMKLocationServiceDelegate,BMKMapViewDelegate,BMKGeoCodeSearchDelegate>//
{
    IndexModel *_indexModel;
    PageModels *_pagesModel;
    NavigationView *_navView;
    NSString *_cityName;
     BMKLocationService* _locService;
    BMKGeoCodeSearch* _geocodesearch;
}
//@property (nonatomic,strong) CLLocationManager *locationManager;
@property (nonatomic,strong) NSArray *CityModelAry;
@property (nonatomic,strong) NSArray *CitysAry;
@property (nonatomic,assign) CGFloat FunCellHight;
@property (nonatomic,strong) NSArray *CityDataAry;
@property (nonatomic,strong) NSArray *CityHeadAry;
@property (nonatomic,strong) MainPageModel *mainPageModel;
@property (nonatomic,strong) WetherModel *weathModel;
@property (nonatomic,strong)  MainPageTableview *tableview;;
@property (nonatomic,copy) NSString *thoroughfare;
@property (nonatomic,assign) BOOL Isyujudian;
@property (nonatomic,copy) NSString *longitude;
@property (nonatomic,copy) NSString *latitude;
@property (nonatomic,strong) NSMutableArray *weathCityAry;
@property (nonatomic,strong) NSMutableDictionary *weathDataDic;
@property (nonatomic,strong) NSCache *memCache;
@property (nonatomic,strong) NSMutableArray *dataArray;
@end

@implementation MainPageController
-(NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

-(NSMutableArray *)weathCityAry{
    if (!_weathCityAry) {
        _weathCityAry = [NSMutableArray array];
    }
    return _weathCityAry;
}

-(NSMutableDictionary *)weathDataDic{
    
    if (!_weathDataDic) {
        _weathDataDic = [NSMutableDictionary dictionary];
    }
    return _weathDataDic;
}

-(NSString *)thoroughfare{
    if (!_thoroughfare) {
        _thoroughfare = @"获取您当前的位置";
    }
    return _thoroughfare;
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.app.myTabBar.tabBar.hidden = NO;
    self.navigationController.navigationBar.hidden=YES;
    self.navigationController.navigationBarHidden = YES;
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
        static dispatch_once_t oneceToken;
    
    dispatch_once(&oneceToken, ^{
        [self DataFromSQL];
        [self MainPageFromSQL];
    });
    
    _locService.delegate = self;
    _geocodesearch.delegate = self;
}
-(void)CreatNaView{
    _navView = [[NavigationView alloc]initWithFrame:CGRectMake(0,0, SCREEN_WIDTH, 64)];
    [_navView.seachBnt addTarget:self action:@selector(searchAction) forControlEvents:UIControlEventTouchUpInside];
    [_navView.cityBnt addTarget:self action:@selector(ToCity:) forControlEvents:UIControlEventTouchUpInside];
    [_navView.weatherBnt addTarget:self action:@selector(WeathAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_navView];
}

#pragma mark---标签数据的网络请求
- (void)getAllCharacterData {
    [[Manager sharedManager]AchiveMainPageDataWhithToSQl:^{
        [self DataFromSQL];
    }];
}
#pragma mark--从数据库获取标签数据
-(void)DataFromSQL{
    
    [CGFdbmBase OpenSQlWhiPathName:@"FirstPage.db"];
    NSInteger TableCount = [CGFdbmBase getTableItemCount:@"FirstPage"];
    if (TableCount!=0) {
        [self.dataArray addObjectsFromArray:[CGFdbmBase ListWhith:@"FirstPage" dicName:@"Dic"]];
        _pagesModel = [[PageModels alloc]initWithDictionary:self.dataArray.firstObject error:nil];
        
        _tableview.pagesModel = _pagesModel;
    }
}
//获取每日精选数据
-(void)RequestGet{
    
    [[Manager sharedManager]AchiveMainpageSectionDataWhithCompletionType:^(id responseObject, DIEError *error) {
        [self MainPageFromSQL];
        
    } ToSQL:^{
        [self MainPageFromSQL];
    }];
}

//数据库获取每日精选数据
-(void)MainPageFromSQL{
    [CGFdbmBase OpenSQlWhiPathName:@"Main.db"];
    NSInteger TableCount = [CGFdbmBase getTableItemCount:@"Main"];
    if (TableCount!=0) {
        
        self.mainPageModel =[[MainPageModel alloc]initWithDictionary:[CGFdbmBase ListWhith:@"Main" dicName:@"data"][0] error:nil];

        _tableview.mainPageModel = self.mainPageModel;
        [_tableview reloadData];
        [_tableview.header endRefreshing];
    }else{
        [_tableview.header endRefreshing];
    }
}

//获取天气数据
-(void)AchiveWeatherDataWhithCityName:(NSString *)cityname AndCode:(NSString *)citycode{
    [[Manager sharedManager]RequestWhithURL:[NSString stringWithFormat:weathUrl,citycode] AndParameter:nil AndCompletionType:^(id responseObject, DIEError *error) {
        
        if ([responseObject[@"status"]isEqualToString:@"SUCCESS"]) {
            WetherModel *model = [[WetherModel alloc]initWithDictionary:responseObject[@"data"] error:nil];
            
            [self.weathDataDic addEntriesFromDictionary:@{cityname:model}];
            if (self.weathDataDic.count==self.weathCityAry.count) {
                
                NSDictionary *dic = self.weathCityAry.firstObject;
                self.weathModel = [self.weathDataDic valueForKey:dic[@"name"]];
                _navView.weathMode = self.weathModel.forecast.firstObject;
            }
        }
    }];
}

/**
 *  操作天气城市数组  对数据进行更改 存档
 */
-(void)MakeSearhAryWhithModel:(NSDictionary *)cityDic{
    
    
    if (cityDic!=nil) {
        /**
         *  如果数组个数为0  则直接添加  不需要遍历
         */
        if (self.weathCityAry.count==0) {
            [self.weathCityAry addObject:cityDic];
        }
        
        NSInteger have = 1;
        NSInteger index =0 ;
        for (NSDictionary *dic in self.weathCityAry) {
            
            if ([cityDic[@"name"] isEqualToString:dic[@"name"]]) {
                have = 2;
                index = [self.weathCityAry indexOfObject:dic];
            }
        }
        
        if (have==1) {
            
            [self.weathCityAry insertObject:cityDic atIndex:0];
            
            if (self.weathCityAry.count>10) {
                
                NSDictionary *dic = self.weathCityAry.lastObject;
                [self.weathDataDic removeObjectForKey:dic[@"name"]];
                [self.weathCityAry removeLastObject];
            }
        }
        
        if (have==2) {
            [self.weathCityAry removeObjectAtIndex:index];
            [self.weathCityAry insertObject:cityDic atIndex:0];
            
            if (self.weathCityAry.count>10) {
                
                NSDictionary *dic = self.weathCityAry.lastObject;
                [self.weathDataDic removeObjectForKey:dic[@"name"]];
                [self.weathCityAry removeLastObject];
            }
        }
        
        [self.weathCityAry writeToFile:[Manager CityAryPath] atomically:YES];
 
    }
}


-(void)WeatherCityAction{

self.weathCityAry = [NSMutableArray arrayWithContentsOfFile:[Manager CityAryPath]];
    
    NSDictionary *dic = [self.Myud valueForKey:@"CityDic"];
    
    [self MakeSearhAryWhithModel:dic];
    
    for (NSDictionary *dic in self.weathCityAry) {
         CityModel *model = [[CityModel alloc]initWithDictionary:dic error:nil];
        
        [self AchiveWeatherDataWhithCityName:model.name AndCode:model.code];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self CreatNaView];
    self.automaticallyAdjustsScrollViewInsets = NO;
  
    [self getAllCharacterData];

    _locService = [[BMKLocationService alloc]init];
    _geocodesearch = [[BMKGeoCodeSearch alloc]init];
    [self locate];//定位
 
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC * 1.0), dispatch_get_main_queue(), ^{
         [self RequestGet];
    });

    [self Creattableview];
    [self WeatherCityAction];
}


#pragma mark 点击天气按钮
-(void)WeathAction{
    WeatherController *weath = [WeatherController new];
    weath.cityNameAry = self.weathCityAry ;//传递用户选择天气的城市
    weath.cityDatadic = self.weathDataDic ;//城市天气数据
    weath.shareModel = _pagesModel.share;
    [self.navigationController pushViewController:weath animated:YES];
}

#pragma mark 点击搜索按钮
-(void)searchAction
{
  SouSuoViewController  *ctl=[[SouSuoViewController alloc] init];
    ctl.hotSeachAry = _pagesModel.hot_search;
    [self.navigationController pushViewController:ctl animated:YES];
}

#pragma mark--城市选择button
-(void)ToCity:(CityButton *)sender{
    
    CitysController *city = [CitysController new];
    city.localCity = sender.text.text;//当前城市传递
    city.hoteCity = [_pagesModel.hot_citys copy];//热门搜索城市数据传递
    [self.navigationController pushViewController:city animated:YES];
    
    city.CityBlock = ^(NSString *cityName){//选择城市后的block回调方法，传递用户所选城市
        
        if (cityName.length==3) {
            sender.titleLabel.font = font(11);
        }
        
        _navView.cityBnt.text.text = cityName;//更换导航栏上城市名称
        [Manager CityLocalAndPinYFromSQlWhithCityName:cityName AndIsNotificayion:YES];
        [self AddCityAction];//添加城市后请求该城市的天气数据
    };
}
#pragma mark---添加城市后请求该城市的天气数据
-(void)AddCityAction{
    NSDictionary *dic = [self.Myud valueForKey:@"CityDic"];
    [self MakeSearhAryWhithModel:dic];
    CityModel *model = [[CityModel alloc]initWithDictionary:dic error:nil];
    [self AchiveWeatherDataWhithCityName:model.name AndCode:model.code];
}
#pragma mark---定位
- (void)locate{
    
    if( [CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied) {//没有打开定位服务
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"打开定位" message:@"建议您打开定位，提高您与钓场距离的准确性" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        }];
        
        UIAlertAction *OKcancel = [UIAlertAction actionWithTitle:@"打开定位" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSURL * url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            if([[UIApplication sharedApplication] canOpenURL:url]) {
                NSURL*url =[NSURL URLWithString:UIApplicationOpenSettingsURLString];
                [[UIApplication sharedApplication] openURL:url];
            }
        }];
        
        [alertController addAction:cancel];
        [alertController addAction:OKcancel];
        [self presentViewController:alertController animated:YES completion:nil];
        
    }else{//打开了
        [_locService startUserLocationService];//开启定位服务
    }
}

/**
 *定位失败后，会调用此函数
 *@param mapView 地图View
 *@param error 错误号，参考CLError.h中定义的错误号
 */
- (void)didFailToLocateUserWithError:(NSError *)error
{
    [_locService stopUserLocationService];
}

/**
 *用户方向更新后，会调用此函数
 *@param userLocation 新的用户位置
 */
- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation
{
    CLLocationCoordinate2D pt=(CLLocationCoordinate2D){0,0};
    pt=(CLLocationCoordinate2D){userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude};
    BMKReverseGeoCodeOption *reverseGeocodeSearchOption = [[BMKReverseGeoCodeOption alloc]init];
    reverseGeocodeSearchOption.reverseGeoPoint = pt;
   [_geocodesearch reverseGeoCode:reverseGeocodeSearchOption];
 
    self.longitude = [NSString stringWithFormat:@"%f",userLocation.location.coordinate.longitude];
    self.latitude = [NSString stringWithFormat:@"%f",userLocation.location.coordinate.latitude];
}

//反地理编码
-(void) onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error
{

    self.thoroughfare = result.address;
    if (result.address.length!=0) {
        _cityName = result.addressDetail.city;
        [_locService stopUserLocationService];
    }
}
//
/**
 *在地图View停止定位后，会调用此函数
 *@param mapView 地图View
 */
- (void)didStopLocatingUser
{

    if (_cityName.length!=0) {
        
        NSString *name = [_cityName substringToIndex:_cityName.length-1];
        if (![name isEqualToString:[self.Myud valueForKey:@"localName"]]) {
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"切换城市" message:[NSString stringWithFormat:@"当前定位到您所在城市为:%@\n是否切换到该城市",_cityName] preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                
            }];
            
            UIAlertAction *OKcancel = [UIAlertAction actionWithTitle:@"切换" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
                _navView.cityBnt.text.text = name;
                [Manager CityLocalAndPinYFromSQlWhithCityName:_navView.cityBnt.text.text AndIsNotificayion:NO];
                
                [self.Myud setValue:_longitude forKey:@"longitude"];
                [self.Myud setValue:_latitude forKey:@"latitude"];
                [self.Myud setValue:_longitude forKey:@"Locallongitude"];
                [self.Myud setValue:_latitude forKey:@"Locallatitude"];
                
                [self.Myud setValue:self.thoroughfare forKey:@"thoroughfare"];
                [[NSNotificationCenter defaultCenter]postNotificationName:@"CityChange" object:self];
                
                [self AddCityAction];

            }];
            
            [alertController addAction:cancel];
            [alertController addAction:OKcancel];
            [self presentViewController:alertController animated:YES completion:nil];
        }
            }
    
    UINavigationController *islan = self.tabBarController.viewControllers[1];
    IslandsController *lan = (IslandsController *)islan.topViewController;
    lan.thoroughfare = self.thoroughfare;
}

-(void)Creattableview{
    
    _tableview = [[MainPageTableview alloc]initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT-64-44) style:UITableViewStyleGrouped];
    _tableview.Maindeleget = self;
    [self.view addSubview:_tableview];
    _tableview.header = [MJDIYHeader headerWithRefreshingTarget:self refreshingAction:@selector(headRefresh)];
}

#pragma mark--下拉刷新
-(void)headRefresh{
    [self WeatherCityAction];
    [self RequestGet];
}

#pragma mark--MainPageTableview 代理方法 用于每日精选点击传递界面
-(void)MainPageTableviewSelect:(NSString *)tid Url:(NSString *)Url Slide:(BOOL)IsSlide Row:(NSInteger)row{
    SeleCtContrl *str = [SeleCtContrl new];
    str.tid = tid;
    str.url = Url;
    str.isSlide = IsSlide;
    str.rowOfCell = row;
    str.deleget = self;
    [self.navigationController pushViewController:str animated:YES];
}

#pragma mark--详情页面点赞回调方法
-(void)SelectAtcPraisWhithCellRow:(NSInteger)rowOfCell{
    if (rowOfCell!=100000) {
        [_tableview SelectPrais:rowOfCell];
    }
}

-(void)PramisNoLogin
{
    LoginController *login = [LoginController new];
    [self.navigationController pushViewController:login animated:YES];
}
-(void)UserSpaceClick:(NSString *)uid{
    OtherInformationCtrl *other = [OtherInformationCtrl new];
    other.uid = uid;
    [self.navigationController pushViewController:other animated:YES];
}

#pragma mark--功能模块点击代理
-(void)FunctionCellSelect:(NSInteger)item{
    if (item==2) {
        UINavigationController *School=  self.tabBarController.viewControllers[2];
        SchoolController *schlCtl = (SchoolController *)School.topViewController;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.05 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            schlCtl.pageController.selectIndex = 2;
        });
    }else if (item==1){
        
        UINavigationController *islan = self.tabBarController.viewControllers[1];
        IslandsController *lan = (IslandsController *)islan.topViewController;
        lan.CharactModel = _pagesModel.diaochang;
        lan.isYuJuDian = YES;
        self.app.myTabBar.selectedIndex = 1;
        
    }else if (item==0){
    
        UINavigationController *islan = self.tabBarController.viewControllers[1];
        IslandsController *lan = (IslandsController *)islan.topViewController;
        lan.CharactModel = _pagesModel.diaochang;
        lan.isYuJuDian = NO;
        self.app.myTabBar.selectedIndex = 1;
    }else if (item==3) { //论坛
        ForumClickController *foru = [ForumClickController new];
        foru.model = _pagesModel.forum;
        [self.navigationController pushViewController:foru animated:YES];
    }else if (item==4) {//渔获
        FunSelectController *funSelct = [FunSelectController new];
        funSelct.fid = 2;
        [self.navigationController pushViewController:funSelct animated:YES];
    }else if (item==5) {//问答
        FunSelectController *funSelct = [FunSelectController new];
        funSelct.fid = 36;
        [self.navigationController pushViewController:funSelct animated:YES];
    }else if (item==6) {//自拍
        FunSelectController *funSelct = [FunSelectController new];
        funSelct.fid = 37;
        [self.navigationController pushViewController:funSelct animated:YES];
    }else if (item==7) {//装备
        FunSelectController *funSelct = [FunSelectController new];
        funSelct.fid = 47;
        [self.navigationController pushViewController:funSelct animated:YES];
    }
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
#pragma mark--正向传值
//    UINavigationController *School=  self.tabBarController.viewControllers[2];
//    SchoolController *schlCtl = (SchoolController *)School.topViewController;
//    if (!schlCtl.Model) {
//        schlCtl.Model = _pagesModel.article;
//    }
    
    UINavigationController *islan = self.tabBarController.viewControllers[1];
    IslandsController *lan = (IslandsController *)islan.topViewController;
    if (!lan.CharactModel) {
        lan.CharactModel = _pagesModel.diaochang;
    }
    lan.thoroughfare = self.thoroughfare;
}


@end